package com.platform.comm.util;

import lombok.extern.log4j.Log4j2;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;


/**
 * 文件上传工具
 *
 * @author rushman
 */
@Log4j2
public class UploadUtil {

    public static final String STD_PS = "/";

    public static String buildStdPath(String... parts) {
        StringBuffer sb = new StringBuffer();
        sb.append(parts[0]);
        for (int i = 1; i < parts.length; i++) {
            sb.append(STD_PS);
            sb.append(parts[i]);
        }
        return sb.toString().replaceAll("\\\\+", STD_PS).replaceAll("/+", STD_PS);
    }

    public static String buildErrorFileName(String uploadUrl, String prefix, String suffix, String extName) {
        String dir = getParentDir(uploadUrl);
        String basename = getBasename(uploadUrl);
        String targetName = String.format("%s%s%s.%s", prefix, basename.replaceAll("\\..*", ""), suffix, extName);

        return (dir == null) ? targetName : buildStdPath(dir, targetName);
    }


    public static String getBasename(String path) {
        return new File(path).getName();
    }

    public static String getParentDir(String path) {
        return new File(path).getParent();
    }

    public static String buildRandomFileName(String sourceFileName) {
        return buildRandomFileName(sourceFileName, null, null);
    }

    public static String buildRandomFileName(String sourceFileName, @NotNull String prefix, String suffix) {
        String randomName = String.format("%s%s%s",
                prefix == null ? "" : prefix,
                UUID.randomUUID().toString(),
                suffix == null ? "" : suffix);

        String dir = getParentDir(sourceFileName);
        String basename = getBasename(sourceFileName);
        String extName = getExtName(basename);
        String targetName = String.format("%s.%s", randomName, extName);

        return (dir == null) ? targetName : buildStdPath(dir, targetName);
    }

    public static String getExtName(String path) {
        String basename = getBasename(path);
        return basename.replaceAll(".*\\.", "");
    }

    public static String getFilePath(MultipartFile uploadFile, String moduleName, String moduleFilePath) {
        String fullFilePath = ProjectUtils.getImportFilePath(moduleName, moduleFilePath);

        File savedFile = new File(fullFilePath);

        if (savedFile.exists()) {
            savedFile.delete();
        } else {
            File parentFile = savedFile.getParentFile();
            if (!parentFile.exists()) {
                parentFile.mkdirs();
            }
        }
        try (FileOutputStream fos = FileUtils.openOutputStream(new File(fullFilePath))) {
            IOUtils.copy(uploadFile.getInputStream(), fos);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            throw new RuntimeException("上传批量导入文件出错");
        }

        return moduleFilePath;
    }
}
